using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.DTO.Hmw;
using net_work.IService.Hmw;

namespace net_work.Controllers.Hmw;

[Route("api/[controller]")]
[ApiController]
public class HomeworkController(ILogger<HomeworkController> logger, IHomeworkService homeworkService) : ControllerBase
{
    /// <summary>
    /// 获取作业列表
    /// </summary>
    /// <param name="request">分页请求实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("list")]
    [Authorize]
    public async Task<IActionResult> ListHomeworks([FromBody] PagedRequest request)
    {
        logger.LogInformation("获取作业列表");
        var result = await homeworkService.GetHomeworksPagedAsync(request);
        return AjaxResult.Success(result);
    }

    /// <summary>
    /// 获取作业信息
    /// </summary>
    /// <param name="homeworkId">作业ID</param>
    /// <returns>操作结果</returns>
    [HttpGet("get")]
    [Authorize]
    public async Task<IActionResult> GetHomeworkById([FromQuery] long homeworkId)
    {
        logger.LogInformation("获取作业信息");
        return await homeworkService.SelectByIdAsync(homeworkId) is { } homework
            ? AjaxResult.Success(homework)
            : AjaxResult.Error();
    }

    /// <summary>
    /// 新增作业
    /// </summary>
    /// <param name="homeworkAddRequest">新增作业实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("add")]
    [Authorize(Roles = "ADMIN,SECRET,TEACHER")]
    public async Task<IActionResult> AddHomework([FromBody] HomeworkAddRequest homeworkAddRequest)
    {
        logger.LogInformation("新增作业");
        var homeworkId = await homeworkService.InsertHomework(homeworkAddRequest);
        return homeworkId > 0
            ? AjaxResult.Success(new { homeworkId })
            : AjaxResult.Error();
    }

    /// <summary>
    /// 修改作业
    /// </summary>
    /// <param name="homeworkUpdateRequest">修改作业实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("update")]
    [Authorize(Roles = "ADMIN,SECRET,TEACHER")]
    public async Task<IActionResult> UpdateHomework([FromBody] HomeworkUpdateRequest homeworkUpdateRequest)
    {
        logger.LogInformation("修改作业");
        return await homeworkService.UpdateHomework(homeworkUpdateRequest) > 0
            ? AjaxResult.Success()
            : AjaxResult.Error();
    }

    /// <summary>
    /// 删除作业
    /// </summary>
    /// <param name="ids">作业ID</param>
    /// <returns>操作结果</returns>
    [HttpPost("delete")]
    [Authorize(Roles = "ADMIN,SECRET,TEACHER")]
    public async Task<IActionResult> DeleteHomework([FromBody] List<long> ids)
    {
        logger.LogInformation("删除作业");
        return await homeworkService.DeleteHomeworkByIds(ids) > 0
            ? AjaxResult.Success()
            : AjaxResult.Error();
    }
}